package cn.lena.weblog.controller;

import cn.lena.weblog.domain.User;
import cn.lena.weblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@RequestMapping("changePass")
	public String changePass(HttpSession session){
		if(session.getAttribute("user")==null){
			return "user/login";	//用户没有登录，或者登录已经失效
		}
		return "user/personal-changePass";
	}

	@RequestMapping("/personal")
	public String personal(HttpSession session){
		if(session.getAttribute("user")==null){
			return "user/login";	//用户没有登录，或者登录已经失效
		}
		return "user/personal";
	}

	@RequestMapping("/findOne")//t
	public String findOne(HttpSession session,Model model){
		User user = (User) session.getAttribute("user");
		if(user!=null){
			model.addAttribute("user",user);
			return "user/personal";
		}
		//如果user是空的需要重新登录
		return "redirect:user";
	}

	@PostMapping("/update")//t
	public String updateUser(User user,HttpSession session,Model model){
		System.out.println("update");
		user.setUserId(((User)session.getAttribute("user")).getUserId());
		int update = userService.update(user);
		if (update==1){
			//会直接覆盖原来的值吗？会。
			user=userService.findByUserId(user.getUserId());
			session.setAttribute("user",user);
			model.addAttribute("updateMsg","更新成功");
			return "user/personal";
		}
		//更新失败
		model.addAttribute("updateMsg","更新个人信息失败");
		return "user/personal";
	}
}
